package com.juyu.miliao.api.service;

import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.common.constant.RedisKeyPrefix;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 检查 发现动态
 * @author xuanqicheng
 */
@Service
public class CheckFindDynamicCommentAndReplyService {

    private static final String SEND_FIND_DYNAMIC_COMMENT_ADN_REPLY_NUMBER_BY_TIME_AND_USERID =
            RedisKeyPrefix.MI_LIAO_API_KEY
                    + "SEND_FIND_DYNAMIC_COMMENT_ADN_REPLY_NUMBER_BY_TIME_AND_USERID:";

    @Autowired
    private UserInfoCache userInfoCache;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 检查用户是否可以发送评论
     * @param userId
     * @param number
     */
    public void checkNumber(long userId, int number) {

        UserCacheVo userInfo = userInfoCache.getUserCacheInfo(userId);

        if(userInfo.getIsVip()!=1&& userInfo.getIsHost()!=1&&userInfo.getIsSvip()!=1
                && userInfo.getIsPlatinumVip() !=1){
            int sendNumber = getSendCommentAndReplyNumber(userId);
            if(sendNumber>=number){
                throw new ConsumeRuntimeException("4111","您今天免费评论的次数已经用完，开通VIP可以无限评论。", HttpStatus.BAD_REQUEST);
            }
        }
    }


    /**
     * 更新当前用户评论的次数
     * @param userId
     */
    public void incrementDynamicCommentAndReplyNumber(long userId) {
        String key = SEND_FIND_DYNAMIC_COMMENT_ADN_REPLY_NUMBER_BY_TIME_AND_USERID+ LocalDate.now().toString()+":"+userId;
        UserCacheVo userInfo = userInfoCache.getUserCacheInfo(userId);
        if(userInfo.getIsVip()!=1&& userInfo.getIsHost()!=1&&userInfo.getIsSvip()!=1 &&userInfo.getIsPlatinumVip()!=1){
            stringRedisTemplate.opsForValue().increment(key,1);

            LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0)
                    .withMinute(0).withSecond(0).withNano(0);

            long expireTime = DateUtil.getTheRemainingTimesOfTheDay(midnight, TimeUnit.MINUTES);

            stringRedisTemplate.expire(key,expireTime,TimeUnit.MINUTES);
        }
    }


    private int getSendCommentAndReplyNumber(long userId) {
        String key = SEND_FIND_DYNAMIC_COMMENT_ADN_REPLY_NUMBER_BY_TIME_AND_USERID+ LocalDate.now().toString()+":"+userId;
        String target =stringRedisTemplate.opsForValue().get(key);
        int sendNumber = 0;
        if(!StringUtils.isEmpty(target)){
            sendNumber = Integer.parseInt(target);
        }
        return sendNumber;
    }
}
